$(document).ready(function () {
    $(document).on('click', '.file-browser', function () {
        var $browser = $(this);
        var file = $browser.closest('.file-group').find('[type="file"]');
        file.on('click', function (e) {
            e.stopPropagation();
        });
        file.trigger('click');
    });

    $(document).on('change', '.file-group [type="file"]', function () {
        var $this = $(this);
        var $input = $(this)[0];
        var $len = $input.files.length;
        var formFile = new FormData();

        if ($len == 0) {
            return false;
        } else {
            var fileaccept = $this.attr('accept');
            var fileType = $input.files[0].type;
            var type = (fileType.substr(fileType.lastIndexOf("/") + 1)).toLowerCase();

            if (!type || fileaccept.indexOf(type) == -1) {
                notify.error('您上传图片的类型不符合'+fileaccept);
                return false;
            }
            formFile.append("file", $input.files[0]);
        }

        var data = formFile;
        var l = $('body').lyearloading({
            opacity: 0.2,
            spinnerSize: 'lg'
        });
        $.ajax({
            url: '/admin/index/upload',
            data: data,
            type: "POST",
            dataType: "json",
            //上传文件无需缓存
            cache: false,
            //用于对data参数进行序列化处理 这里必须false
            processData: false,
            //必须
            contentType: false,
            success: function (res) {
                l.destroy();
                if (res.code === 200) {
                    notify.success("上传成功");
                    $this.closest('.file-group').find('.file-value').val(res.data.fullPath);
                } else {
                    notify.error(res.msg);
                }
            },
            error:function(){
                l.destroy();
                notify.error("服务器错误");
            }
        });
    });
});

$(document).ready(function () {
    $(document).on('click', '.file-apk', function () {
        var $browser = $(this);
        var file = $browser.closest('.file-apkgroup').find('[type="file"]');
        file.on('click', function (e) {
            e.stopPropagation();
        });
        file.trigger('click');
    });

    $(document).on('change', '.file-apkgroup [type="file"]', function () {
        var $this = $(this);
        var $input = $(this)[0];
        var $len = $input.files.length;
        var formFile = new FormData();

        if ($len == 0) {
            return false;
        } else {
            var fileType = '';
    
            // 判断浏览器类型
            var isFirefox = typeof InstallTrigger !== 'undefined';
            if (isFirefox) {
                var fileName = $input.files[0].name;
                var fileExtension = fileName.split('.').pop().toLowerCase();
                
                // 检查文件扩展名是否为 .apk
                if (fileExtension !== 'apk') {
                    notify.error('请选择有效的 .apk 文件');
                    return false;
                }
                
                fileType = fileExtension;
            } else {
                fileType = $input.files[0].type;
                
                // 检查文件类型是否为空
                if (!fileType) {
                    notify.error('无法获取文件类型，请选择有效的 .apk 文件');
                    return false;
                }
    
                // 假设这里使用 MIME 类型检查的逻辑
                var acceptedMimeTypes = ['application/vnd.android.package-archive']; // 添加其他允许的 MIME 类型
    
                // 检查文件类型是否在接受的类型列表中
                if (acceptedMimeTypes.indexOf(fileType) === -1) {
                    notify.error('您上传软件的类型不符合');
                    return false;
                }
            }
    
            formFile.append("file", $input.files[0]);
        }

        var data = formFile;
        var l = $('body').lyearloading({
            opacity: 0.2,
            spinnerSize: 'lg'
        });
        $.ajax({
            url: '/admin/index/upload',
            data: data,
            type: "POST",
            dataType: "json",
            //上传文件无需缓存
            cache: false,
            //用于对data参数进行序列化处理 这里必须false
            processData: false,
            //必须
            contentType: false,
            success: function (res) {
                l.destroy();
                if (res.code === 200) {
                    notify.success("上传成功");
                    $this.closest('.file-apkgroup').find('.file-apkvalue').val(res.data.fullPath);
                } else {
                    notify.error(res.msg);
                }
            },
            error:function(){
                l.destroy();
                notify.error("服务器错误");
            }
        });
    });
});

$(document).ready(function () {
    $(document).on('click', '.file-browsers', function () {
        var $browser = $(this);
        var file = $browser.closest('.file-groups').find('[type="file"]');
        file.on('click', function (e) {
            e.stopPropagation();
        });
        file.trigger('click');
    });

    $(document).on('change', '.file-groups [type="file"]', function () {
        var $this = $(this);
        var $input = $(this)[0];
        var $len = $input.files.length;
        var formFile = new FormData();
		var temp = document.getElementById('file_list_more_pic');
		var numold = temp.getElementsByTagName("li").length;
		if(numold >= 4){
			notify.error("最多上传4张截图");
			return;
		}
        if ($len == 0) {
            return false;
        } else {
            var fileaccept = $this.attr('accept');
            var fileType = $input.files[0].type;
            var type = (fileType.substr(fileType.lastIndexOf("/") + 1)).toLowerCase();

            if (!type || fileaccept.indexOf(type) == -1) {
                notify.error('您上传图片的类型不符合'+fileaccept);
                return false;
            }
            formFile.append("file", $input.files[0]);
        }

        var data = formFile;
        var l = $('body').lyearloading({
            opacity: 0.2,
            spinnerSize: 'lg'
        });
        $.ajax({
            url: '/admin/index/upload',
            data: data,
            type: "POST",
            dataType: "json",
            //上传文件无需缓存
            cache: false,
            //用于对data参数进行序列化处理 这里必须false
            processData: false,
            //必须
            contentType: false,
            success: function (res) {
                l.destroy();
                if (res.code === 200) {
                    notify.success("上传成功");
                    // $this.closest('.file-group').find('.file-value').val(res.data.filePath);
					
					// console.log(numold)
					
					// notify.error(numold);
                    var str=$('#file_list_more_pic').html();
					var imgurl=$('.file-values').val();
					if(numold==0){
						imgurl+=res.data.fullPath;
					}else{
						imgurl+=','+res.data.fullPath;
					}
					$('.file-values').val(imgurl);
                    var add=
                    '<li class="col-xs-4 col-sm-t3" id="delsec">'+
                    '<figure>'+
                    '<img src="' + 
                    res.data.fullPath +
                    '">'+
                    '<figcaption>'+
                    '<div class="btn btn-round btn-square btn-danger" >'+
                    '<i class="mdi mdi-delete">'+
                    '</i>'+
                    '</div>'+
                    '</figure>'+
                    '</li>';
                    str+=add;
                    $('#file_list_more_pic').html(str);
                } else {
                    notify.error(res.msg);
                }
            },
            error:function(){
                l.destroy();
                notify.error("服务器错误");
            }
        });
    });
	
	$(document).on('click', '#delsec', function () {
		// var obj = document.getElementById("file_list_more_pic");
		var obj = document.getElementById("file_list_more_pic");
		var imgurl = $(this).find("img").attr("src");
		console.log('删除链接：'+imgurl)
		var imgurls = $('.file-values').val();
		if(imgurls.indexOf(','+imgurl) !== -1){
		　　imgurls = imgurls.replace(','+imgurl,'');
		}else if(imgurls.indexOf(imgurl+',') !== -1){
			imgurls = imgurls.replace(imgurl+',','');
		}else{
			imgurls = imgurls.replace(imgurl,'');
		}		
		$('.file-values').val(imgurls);
		console.log('最终链接：'+imgurls)
		obj.removeChild(this);
	});
});


$.fn.ghostsf_serialize = function () {
    var a = this.serializeArray();
    var $radio = $('input[type=radio],input[type=checkbox]', this);
    $.each($radio, function () {
        if ($("input[name='" + this.name + "']").is(':checked')) {
            console.log(this.name + " is checked!");
            for (var k = 0; k < a.length; k++) {
                if (a[k].name == this.name) {
                    a[k].value = true;
                    break;
                }
            }
        } else {
            var find = false;
            for (var k = 0; k < a.length; k++) {
                if (a[k].name == this.name) {
                    a[k].value = false;
                    find = true;
                    break;
                }
            }
            if (!find) {
                a.push({ name: this.name, value: false });
            }
        }

    });
    var $num = $('input[type=number]', this);
    $.each($num, function () {
        for (var k = 0; k < a.length; k++) {
            if (a[k].name == this.name) {
                a[k].value = Number(a[k].value);
                break;
            }
        }
    });

    return a;
};

$.fn.parseForm = function () {
    let serializeObj = {};
    let array = this.ghostsf_serialize();
    let str = this.serialize();
    $(array).each(function () {
        if (serializeObj[this.name]) {
            if ($.isArray(serializeObj[this.name])) {
                serializeObj[this.name].push(this.value);
            } else {
                serializeObj[this.name] = [serializeObj[this.name], this.value];
            }
        } else {
            serializeObj[this.name] = this.value;
        }
    });
    return serializeObj;
};

function randomString(length) {
    var chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var result = '';
    for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
    return result;
}